const regeneratorRuntime = require("../../utils/runtime.js")
const login = require('../../utils/utils.js')
const {
  _post,
  _get,
  _request
} = require('../../utils/request.js')

import Notify from '/@vant/weapp/notify/notify'

// 计算时间差
function calcDate(dateTimeStamp, minute = 60000, hour = 3600000, day = 86400000) {
  var result = ''
  var now = new Date().getTime()
  var diffValue = now - dateTimeStamp
  if (diffValue < 0) {
    return result = "刚刚"
  }
  var dayC = diffValue / day
  var hourC = diffValue / hour
  var minC = diffValue / minute
  if (parseInt(dayC) > 30) {
    result = "" + this.$format(dateTimeStamp, "yyyy-MM-dd")
  } else if (parseInt(dayC) > 1) {
    result = "" + parseInt(dayC) + "天前"
  } else if (parseInt(dayC) == 1) {
    result = "昨天"
  } else if (hourC >= 1) {
    result = "" + parseInt(hourC) + "小时前"
  } else if (minC >= 5) {
    result = "" + parseInt(minC) + "分钟前"
  } else
    result = "刚刚"
  return result
}
Page({
  data: {
    articleList: {},
    isFirstLoad: true,
    collectionTags: [],
    selectedTag: [],
    sortedList: null
  },

  handleCellClick(e) {
    wx.navigateTo({
      url: '/pages/article/article?id=' + e.currentTarget.dataset.id,
    })
  },

  async onLoad() {
    await this.getCollections()
  },


  async getCollections() {
    let res = await _get('/article', {
      collection: 1,
      page: 1,
      limit: 5000
    })
    let articleList = res.data,
      collectionTags = []
    if (articleList.list && articleList.list instanceof Array) {
      for (let i = 0; i < articleList.list.length; i++) {
        articleList['list'][i]['add_time'] = calcDate(new Date(articleList['list'][i]['add_time']).valueOf())
        if (articleList['list'][i]['label'] && articleList['list'][i]['label'] instanceof Array) {
          collectionTags = collectionTags.concat(articleList['list'][i]['label'])
        }
      }
    }
    if (res.code === 0) {
      this.setData({
        articleList,
        isFirstLoad: false,
        collectionTags: [...new Set(collectionTags)]
      })
    }
  },

  handleGetSelectedTag(e) {
    let tags = e.detail.tags,
      list = this.data.articleList.list,
      sorted = {}, isEmpty = true
    for (let i = 0; i < list.length; i++) {
      if (list[i]['label'] && list[i]['label'] instanceof Array) {
        for (let k in tags) {
          if (list[i]['label'].includes(k) && tags[k]) {
            sorted[list[i]['id']] = list[i]
            isEmpty = false
          }
        }
      }
    }
    this.setData({
      selectedTag: e.detail.tags,
      sortedList: isEmpty ? [] : sorted
    })
  },

  async handleRemoveCollection(e) {
    let res = await _request('/collection', 'DELETE', {
      cid: e.currentTarget.dataset.id * 1
    })

    if (res.code === 0) {
      Notify({
        type: 'success',
        message: '已移除'
      })
      await this.getCollections()
    }
  },

  async onShow() {
    if(this.data.articleList.list) {
      await this.getCollections()
    }
  }
})